package com.xindaoapp.happypet.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

@SuppressLint("NewApi")
public class VideoPreviewActivity extends UMBaseActivity implements
        TextureView.SurfaceTextureListener, OnClickListener, OnCompletionListener {

    /** 视频地址 */
    private String mVideoPath;
    private TextureView surfaceView;
    private Button cancelBtn;
    private MediaPlayer mediaPlayer;
    private ImageView imagePlay;
    private View mPlayUseView;

    private int mCurrentPosition = 0;
    private View[] mStateViews;
    private List<String> mCoverImages;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ffmpeg_preview);

        cancelBtn = (Button) findViewById(R.id.play_cancel);
        cancelBtn.setOnClickListener(this);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        surfaceView = (TextureView) findViewById(R.id.preview_video);

        RelativeLayout preview_video_parent =
                (RelativeLayout) findViewById(R.id.preview_video_parent);
        LayoutParams layoutParams = (LayoutParams) preview_video_parent.getLayoutParams();
        layoutParams.width = displaymetrics.widthPixels;
        layoutParams.height = displaymetrics.widthPixels;
        preview_video_parent.setLayoutParams(layoutParams);

        surfaceView.setSurfaceTextureListener(this);
        surfaceView.setOnClickListener(this);

        mVideoPath = getIntent().getStringExtra(Constants.PARAM_VIDEO_PATH);

        imagePlay = (ImageView) findViewById(R.id.previre_play);
        imagePlay.setOnClickListener(this);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);

        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("视频处理中...");
        dialog.show();
        parseImageCovers(new IRequest<List<String>>() {

            @Override
            public void request(List<String> t) {
                mCoverImages = t;
                initCovers(mCoverImages);
                dialog.dismiss();
                mPlayUseView.setVisibility(View.VISIBLE);
            }
        });
    }

    private void parseImageCovers(final IRequest<List<String>> iRequest) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();

                mediaMetadataRetriever.setDataSource(mVideoPath);
                long duration =
                        Long.parseLong(mediaMetadataRetriever
                                .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
                final List<String> files = new ArrayList<String>();

                CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/happypet/covers/");
                String parentFilePath =
                        Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/happypet/covers/" + System.currentTimeMillis();
                CommonUtil.mkFiledir(parentFilePath);
                for (int i = 0; i < duration / 1000; i++) {
                    String filePath =
                            parentFilePath + File.separator + System.currentTimeMillis() + ".jpg";
                    if (bitmapToFile(mediaMetadataRetriever.getFrameAtTime(i * 1000000,
                            MediaMetadataRetriever.OPTION_CLOSEST_SYNC), filePath)) {
                        files.add(filePath);
                    }
                }
                HappyPetApplication.mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        iRequest.request(files);
                    }
                });
            }
        }).start();
    }

    private boolean bitmapToFile(Bitmap bitmap, String filePath) {
        FileOutputStream fos = null;
        try {
            // create a file to write bitmap data
            File f = new File(filePath);
            f.createNewFile();

            // Convert bitmap to byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
            byte[] bitmapdata = bos.toByteArray();

            // write the bytes in file
            fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            return true;
        } catch (Exception e) {
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 初始化封面
     */
    private void initCovers(List<String> list) {
        mPlayUseView = findViewById(R.id.play_use);
        mPlayUseView.setOnClickListener(this);

        LinearLayout container = (LinearLayout) findViewById(R.id.container);

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        if (null != list) {
            mStateViews = new View[list.size()];

            for (int i = 0; i < list.size(); i++) {
                final View view = getLayoutInflater().inflate(R.layout.item_image, null);
                final ImageView imageView = (ImageView) view.findViewById(R.id.icon);
                android.view.ViewGroup.LayoutParams params =
                        new LayoutParams(metric.widthPixels / 4, metric.widthPixels / 4);
                ImageLoader.getInstance().displayImage("file://" + list.get(i), imageView);
                mStateViews[i] = view.findViewById(R.id.state);
                final int index = i;
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        setState(index);
                    }
                });
                container.addView(view, params);
            }
            setState(0);
        }
    }

    private void setState(int position) {
        mCurrentPosition = position;
        for (int i = 0; i < mStateViews.length; i++) {
            if (i == position) {
                mStateViews[i].setVisibility(View.VISIBLE);
            } else {
                mStateViews[i].setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onStop() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            imagePlay.setVisibility(View.GONE);
        }
        super.onStop();
    }

    private void prepare(Surface surface) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(mVideoPath);
            mediaPlayer.setSurface(surface);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            mediaPlayer.seekTo(0);
        } catch (Exception e) {
        }
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1, int arg2) {
        prepare(new Surface(arg0));
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
        return false;
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1, int arg2) {

    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture arg0) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_cancel:
                stop();
                break;
            case R.id.previre_play:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                }
                imagePlay.setVisibility(View.GONE);
                break;
            case R.id.preview_video:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    imagePlay.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.play_use:
                Intent data = new Intent(Constants.ACTION_VIDEO_END);
                data.putExtra(Constants.PARAM_VIDEO_PATH, mVideoPath);
                if (null != mCoverImages) {
                    data.putExtra(Constants.PARAM_COVER_PATH, mCoverImages.get(mCurrentPosition));
                }
                sendBroadcast(data);
                finish();
                break;
            default:
                break;
        }
    }

    private void stop() {
        mediaPlayer.stop();
        Intent intent = new Intent(this, RecordActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        stop();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        imagePlay.setVisibility(View.VISIBLE);
    }

}
